﻿using CRMClient.Models;
using CRMClient.Models.Contact;
using Microsoft.Phone.Net.NetworkInformation;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace CRMClient.ViewModels
{
    public class ContactViewModel : INotifyPropertyChanged
    {
        private String findalluri = "http://www.mobiblanc.com:2080/proxymobiblanc3/service/gestcontact/findall";
        private String adduri = "http://www.mobiblanc.com:2080/proxymobiblanc3/service/gestcontact/addcontact";
        private String deluri = "http://www.mobiblanc.com:2080/proxymobiblanc3/service/gestcontact/delcontact";
        private String upduri = "http://www.mobiblanc.com:2080/proxymobiblanc3/service/gestcontact/updcontact";
        
        private WebClient client;
        private Response _contact;
        public Response Contact
        {
            get
            {
                return _contact;
            }

            set
            {
                if (value != _contact)
                {
                    _contact = value;
                    NotifyPropertyChanged("Contact");
                }
            }
        }
        private ObservableCollection<Response> _contacts = new ObservableCollection<Response>();

        public ObservableCollection<Response> Contacts
        {
            get
            {
                return _contacts;
            }
            set
            {
                if (value != _contacts)
                {
                    _contacts = value;
                    NotifyPropertyChanged("Contacts");
                }
            }
        }

        private Visibility _loader;
        public Visibility Loader
        {
            get
            {
                return _loader;
            }
            set
            {
                if (value != _loader)
                {
                    _loader = value;
                    NotifyPropertyChanged("Loader");
                }
            }
        }
        private Visibility _contentPanel;
        public Visibility ContentPanel
        {
            get
            {
                return _contentPanel;
            }
            set
            {
                if (value != _contentPanel)
                {
                    _contentPanel = value;
                    NotifyPropertyChanged("ContentPanel");
                }
            }
        }

        private Visibility _sync;
        public Visibility Sync
        {
            get
            {
                return _sync;
            }
            set
            {
                if (value != _sync)
                {
                    _sync = value;
                    NotifyPropertyChanged("Sync");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public void load()
        {
            if (!IsolatedStorageSettings.ApplicationSettings.Contains("contactslist"))
            {
                Loader = Visibility.Visible;
                ContentPanel = Visibility.Collapsed;
                Sync = Visibility.Collapsed;
                if (DeviceNetworkInformation.IsNetworkAvailable)
                {
                    load_data();
                }
                else
                {
                    MessageBox.Show("This app requires a network connection, but no connection was detected.");
                }
            }
            else
            {
                Loader = Visibility.Collapsed;
                ContentPanel = Visibility.Visible;
                Sync = Visibility.Visible;
                Contacts = (ObservableCollection<Response>)IsolatedStorageSettings.ApplicationSettings["contactslist"];
                if (DeviceNetworkInformation.IsNetworkAvailable)
                {
                    load_data();
                }
                else
                {
                    MessageBox.Show("This app requires a network connection for synchronization, but no connection was detected.");
                }
            }
            
        }

        public void load_data()
        {
            client = new WebClient();
            client.DownloadStringCompleted += findall_DownloadStringCompleted;
            client.DownloadStringAsync(new Uri(findalluri + "/" + DateTime.UtcNow.Ticks));
        }

        public void add(String firstname,String lastname,String jobtitle,String businessphone, String mobilephone,String fax,String email,String city,String state,String zip,String country)
        {
            if (DeviceNetworkInformation.IsNetworkAvailable)
            {
                if (firstname.Equals(""))
                    firstname = "%20";
                if (jobtitle.Equals(""))
                    jobtitle = "%20";
                if (businessphone.Equals(""))
                    businessphone = "%20";
                if (mobilephone.Equals(""))
                    mobilephone = "%20";
                if (fax.Equals(""))
                    fax = "%20";
                if (email.Equals(""))
                    email = "%20";
                if (city.Equals(""))
                    city = "%20";
                if (state.Equals(""))
                    state = "%20";
                if (zip.Equals(""))
                    zip = "%20";
                if (country.Equals(""))
                    country = "%20";
                String uri = adduri +  "/" + firstname + "/" + lastname + "/" + jobtitle + "/" + businessphone + "/" + mobilephone+"/"+fax+"/"+email+"/"+ city+"/"+state+"/"+zip+"/"+country+ "/" + DateTime.UtcNow.Ticks;
                client = new WebClient();
                client.DownloadStringCompleted += upd_DownloadStringCompleted;
                client.DownloadStringAsync(new Uri(uri));
            }
        }

        public void del()
        {
            if (DeviceNetworkInformation.IsNetworkAvailable)
            {
                String uri = deluri + "/" + Contact.contactid + "/" + DateTime.UtcNow.Ticks;
                client = new WebClient();
                client.DownloadStringCompleted += upd_DownloadStringCompleted;
                client.DownloadStringAsync(new Uri(uri));
            }
        }

        public void upd(String firstname,String lastname,String jobtitle,String businessphone,String mobilephone,String fax,String email,String city,String state,String zip,String country)
        {
            if (DeviceNetworkInformation.IsNetworkAvailable)
            {
                if (firstname.Equals(""))
                    firstname = "%20";
                if (jobtitle.Equals(""))
                    jobtitle = "%20";
                if (businessphone.Equals(""))
                    businessphone = "%20";
                if (mobilephone.Equals(""))
                    mobilephone = "%20";
                if (fax.Equals(""))
                    fax = "%20";
                if (email.Equals(""))
                    email = "%20";
                if (city.Equals(""))
                    city = "%20";
                if (state.Equals(""))
                    state = "%20";
                if (zip.Equals(""))
                    zip = "%20";
                if (country.Equals(""))
                    country = "%20";
                String uri = upduri + "/" + Contact.contactid + "/" + firstname + "/" + lastname + "/" + jobtitle + "/" + businessphone + "/" + mobilephone+"/"+fax+"/"+email+"/"+ city+"/"+state+"/"+zip+"/"+country+ "/" + DateTime.UtcNow.Ticks;
                client = new WebClient();
                client.DownloadStringCompleted += upd_DownloadStringCompleted;
                client.DownloadStringAsync(new Uri(uri));
            }
        }
        private void findall_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                var deserialized = JsonConvert.DeserializeObject<RootObject>(e.Result);
                if (deserialized.header.status.Equals("OK"))
                {
                    Contacts = new ObservableCollection<Response>(deserialized.response);
                    Loader = Visibility.Collapsed;
                    Sync = Visibility.Collapsed;
                    ContentPanel = Visibility.Visible;
                }
                else
                {
                    MessageBox.Show(deserialized.header.message);
                }
            }
            catch (System.Reflection.TargetInvocationException t)
            {
                MessageBox.Show("An error occurred while connecting to the server", "Error", MessageBoxButton.OK);
            }
            catch (Newtonsoft.Json.JsonReaderException t2)
            {
                MessageBox.Show("An error occurs while reading server response", "Error", MessageBoxButton.OK);
            }
        }

        private void upd_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
        {
            try
            {
                var deserialized = JsonConvert.DeserializeObject<ResponseOp>(e.Result);
                MessageBox.Show(deserialized.header.message);   
            }
            catch (System.Reflection.TargetInvocationException t)
            {
                MessageBox.Show("An error occurred while connecting to the server", "Error", MessageBoxButton.OK);
            }
            catch (Newtonsoft.Json.JsonReaderException t2)
            {
                MessageBox.Show("An error occurs while reading server response", "Error", MessageBoxButton.OK);
            }
        }

        public void saveOnCache()
        {
            if (Contacts.Count != 0)
                IsolatedStorageSettings.ApplicationSettings["contactslist"] = Contacts;
        }
    }
    }

